﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StuWebApi.Dto;
using StuWebApi.Entity;

namespace StuWebApi.Controllers;

[ApiController]
[Route("[controller]")]
public class StudentsController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public StudentsController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
    {
        return await _context.Students
            .Include(s => s.Classroom)
            .ThenInclude(c => c.School)
            .Include(s => s.School)
            .ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<Student>> GetStudent(int id)
    {
        var student = await _context.Students
            .Include(s => s.Classroom)
            .ThenInclude(c => c.School)
            .Include(s => s.School)
            .FirstOrDefaultAsync(s => s.StudentId == id);

        if (student == null)
        {
            return NotFound();
        }

        return student;
    }

    [HttpPost]
    public async Task<ActionResult<Student>> PostStudent(StudentDto studentDto)
    {
        var student = new Student
        {
            Name = studentDto.Name,
            Age = studentDto.Age,
            ClassroomId = studentDto.ClassroomId,
            SchoolId = studentDto.SchoolId
        };

        _context.Students.Add(student);
        await _context.SaveChangesAsync();

        await LogAction("Create", $"Student {student.Name} created.");

        return CreatedAtAction(nameof(GetStudent), new { id = student.StudentId }, student);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> PutStudent(int id,  StudentDto studentDto)
    {
        var student = await _context.Students.FindAsync(id);
        if (student == null)
        {
            return NotFound();
        }

        student.Name = studentDto.Name;
        student.Age = studentDto.Age;
        student.ClassroomId = studentDto.ClassroomId;
        student.SchoolId = studentDto.SchoolId;

        _context.Entry(student).State = EntityState.Modified;
        await _context.SaveChangesAsync();

        await LogAction("Update", $"Student {student.Name} updated.");

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteStudent(int id)
    {
        var student = await _context.Students.FindAsync(id);
        if (student == null)
        {
            return NotFound();
        }

        _context.Students.Remove(student);
        await _context.SaveChangesAsync();

        return NoContent();
    }
    
    private async Task LogAction(string action, string description)
    {
        var log = new Log
        {
            Timestamp = DateTime.UtcNow,
            Action = action,
            Description = description
        };
        _context.Logs.Add(log);
        await _context.SaveChangesAsync();
    }
}
